package com.mtk.launcher.util;

import android.util.Log;

import com.lark.wifi.util.MyLog;
import com.mtk.launcher.config.AppConfig;
import com.mtk.launcher.runnable.FileWriteToSdInfoRunnable;
import com.mtk.launcher.service.MyService;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

    public static void creatPathNotExcit(String printTag) {
        try {
            List<String> listsPath = getCreateFileList();
            for (int i = 0; i < listsPath.size(); i++) {
                String filePath = listsPath.get(i);
                File file = new File(filePath);
                if (!file.exists()) {
                    boolean isCreate = file.mkdirs();
                    Log.e("cdl", "creatPathNotExcit=" + isCreate + "/" + filePath);
                }
            }
        } catch (Exception e) {
            Log.e("cdl", "creatPathNotExcit=" + e.toString());
            e.printStackTrace();
        }
    }

    private static List<String> getCreateFileList() {
        List<String> listsPath = new ArrayList<String>();
        listsPath.add(AppConfig.CRACH_PATH);
        listsPath.add(AppConfig.LAUNCHER_PATH);
        listsPath.add(AppConfig.LOG_PATH);
        return listsPath;
    }

    public static void MKDIRSfILE(String path) {
        File file = null;
        try {
            file = new File(path);
            if (!file.exists()) {
                boolean isCreate = file.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将信息写入SD卡
     *
     * @param registerPath
     * @param wirteJson
     */
    public static void writeMessageInfoToTxt(String registerPath, String wirteJson) {
        FileWriteToSdInfoRunnable runnable = new FileWriteToSdInfoRunnable(wirteJson, registerPath);
        MyService.getInstance().executor(runnable);
    }

    /***
     * 删除软件运行的日志
     * @param filePath
     */
    public static void checkCrashLogFileSize(String filePath) {
        MyLog.e("cdl", "checkCrashLogFileSize==filePath=" + filePath);
        if (!AppConfig.PERMISSION_COMPLAIY) {
            return;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            creatPathNotExcit("检查文件路径");
            return;
        }
        File[] fileList = file.listFiles();
        if (fileList == null || fileList.length < 1) {
            MyLog.e("cdl", "checkCrashLogFileSize==0");
            return;
        }
        MyLog.e("cdl", "checkCrashLogFileSize==" + fileList.length);
        if (fileList.length < 10) {
            return;
        }
        //大于10个，就删除5个，保留5——10 个即可
        for (int i = 0; i < 5; i++) {
            File fileDel = fileList[i];
            boolean isDel = fileDel.delete();
            MyLog.e("cdl", "checkCrashLogFileSize=删除文件=" + isDel + " - " + fileDel.getPath());
        }
    }
}
